<template>
    <div class="person-position-container">
        <!-- 数据表格 -->
        <el-card>
            <el-form class="search-form" ref="searchFormRef" :inline="true">
                <el-form-item>
                    <div style="float: left;">
                        <FolderSelector :tree-data="fileTree" @folder-selected="handleFolderSelected" />
                    </div>

                </el-form-item>
                <el-form-item>
                    <el-select v-model="searchForm.imageFormat" class="m-2" placeholder="筛选图片格式" size="large" clearable
                        style="width: 140px">
                        <el-option v-for="item in filterOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="searchForm.fileType" class="m-2" placeholder="档案门类" size="large"
                        style="width: 120px">
                        <el-option label="全部" value="" />
                        <el-option label="照片" value="ZP" />
                        <el-option label="录音" value="LY" />
                        <el-option label="录像" value="LX" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="searchForm.isMovedToArchive" class="m-2" placeholder="是否移馆" size="large" style="width: 120px" clearable @change="handleSearch">
                        <el-option label="移馆" :value="1" />
                        <el-option label="不移馆" :value="2" />
                        <el-option label="资料" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="searchForm.fileSize" placeholder="文件大小(KB)" size="large" clearable style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                </el-form-item>
                <el-form-item class="search-right-btns" style="margin-right:0;">
                    <el-upload class="import-btn" action="" :auto-upload="false" :show-file-list="false" :on-change="handleExcelImport" accept=".xlsx,.xls">
                        <el-button type="primary">导入Excel文件</el-button>
                    </el-upload>
                    <el-button type="primary" @click="handleImport" class="import-btn">
                        导入目录<el-icon class="el-icon--right"><document-add /></el-icon>
                    </el-button>
                    <el-dropdown @command="handleExport">
                        <el-button type="success">
                            导出数据<el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="filted">导出当前表格数据</el-dropdown-item>
                                <el-dropdown-item command="moved">导出全部移馆数据</el-dropdown-item>
                                <el-dropdown-item command="notMoved">导出全部不移馆数据</el-dropdown-item>
                                <el-dropdown-item command="searchAll">导出当前搜索全部数据</el-dropdown-item>
                                <el-dropdown-item command="all">导出全部数据</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </el-form-item>
            </el-form>
            <div style="margin-bottom:15px;">
                <el-button type="primary" @click="handleBatchRemove(true)" :disabled="selectedItems.length === 0">
                    批量移馆
                </el-button>
                <el-button class="import-btn" type="warning" @click="handleBatchRemove(false)" :disabled="selectedItems.length === 0">
                    批量不移馆
                </el-button>
                <!-- 添加新的批量迁移按钮 -->
                <el-dropdown class="import-btn" trigger="hover" @command="handleBatchMove"  :disabled="selectedItems.length === 0">
                    <el-button type="danger" :disabled="selectedItems.length === 0">批量迁移照片<el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="0">不移管类型</el-dropdown-item>
                            <el-dropdown-item command="1">资料移管类型</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <!-- 添加档案号重编下拉菜单 -->
                <el-dropdown class="import-btn" trigger="hover" @command="handleRenumber">
                    <el-button type="primary">档案号重编<el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item v-for="year in availableYears" :key="year" :command="year">
                                {{ year }}
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <!-- 添加重命名word菜单 -->
                <el-button type="primary" @click="showRenameWordDialog">重命名Word</el-button>

            </div>

            <el-table ref="multipleTableRef" :data="tableData" @selection-change="handleSelectionChange" border
                style="width: 100%">
                <!-- 复选框列 -->
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="fileNumber" width="300" label="档号" />
                <el-table-column label="图片预览" align="center" width="100">
                    <template #default="{ row }">
                        <el-image v-if="row.imgSrc" lazy style="max-height: 80px;max-width: 80px;" :src="row.imgSrc"
                            :preview-src-list="[row.imgSrc]" fit="fill" :zoom-rate="1.2" :preview-teleported="true" />
                    </template>
                </el-table-column>
                <el-table-column prop="imageTitle" label="图片题名" width="350" />
                <el-table-column prop="shootingDate" label="拍摄日期" width="150" align="center" />
                <el-table-column prop="shootingLocation" label="拍摄地点" width="250" align="center" />
                <el-table-column prop="eventReason" label="事由" width="250" align="center" />
                <el-table-column label="人物" width="180">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span v-for="(person, index) in getPersonList(scope.row.extendedData)" :key="index">{{
                                `${person.position}${person.name}(${person.positionInImage})` }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="单位/摄影者" width="180">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            {{ getOrgName(scope.row.organization) }} {{ scope.row.journalists }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="图片信息" width="180">
                    <template #default="{ row }">
                        <div style="display: flex; align-items: center">
                            {{ getImageInfo(row) }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="imageFormat" label="图片格式" align="center" />
                <!-- 添加图片路径列 -->
                <el-table-column prop="imagePath" label="图片路径" width="250">
                    <template #default="{ row }">
                        <el-tooltip :content="row.imagePath" placement="top">
                            <div class="ellipsis-text">{{ row.imagePath }}</div>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <!-- 添加图片分辨率列 -->
                <el-table-column label="图片分辨率" width="120" align="center">
                    <template #default="{ row }">
                        {{ row.imageScale }}
                    </template>
                </el-table-column>
                <el-table-column prop="isMovedToArchive" label="是否移馆" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag v-if="!isNull(row.isMovedToArchive)" :type="row.isMovedToArchive ? 'success' : 'info'">
                            {{  row.isMovedToArchive ? '是' : '否' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right" align="center">
                    <template #default="{ row }">
                        <el-button type="success" size="small" @click="handleEdit(row)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100, 1000000]"
                    :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total"></el-pagination>
            </div>
        </el-card>

        <!-- 导入目录对话框 -->
        <el-dialog :width="300" v-model="importDialogVisible" :before-close="cancelImport">
            <div class="folder-selector-container">
                <label>导入目录：</label>
                <FolderSelector 
                    :tree-data="tempFileTree" 
                    @folder-selected="handleImportFolderSelect"
                    :selected-folder="selectedImportFolder"
                    :directories="true"
                />
            </div>
            <div class="dialog-actions">
                <el-button @click="cancelImport">取消</el-button>
                <el-button type="primary" @click="confirmImport" :disabled="!selectedImportFolder">
                    导入
                </el-button>
            </div>
        </el-dialog>
        
        <!-- 重命名Word文档对话框 -->
        <el-dialog title="重命名Word文档" v-model="renameWordDialogVisible" width="400px" :before-close="cancelRenameWord">
            <el-form ref="renameWordFormRef" :model="renameWordForm" label-width="80px">
                <el-form-item label="名称" prop="rootPath" :rules="[{ required: true, message: '请输入名称', trigger: 'blur' }]">
                    <el-input v-model="renameWordForm.rootPath" placeholder="请输入名称" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancelRenameWord">取消</el-button>
                    <el-button type="primary" @click="confirmRenameWord">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElDialog } from 'element-plus'
import {
    getFileTree,
    searchNewsPhotos,
    batchUpdateArchiveStatus,
    batchMoveArchive,
    importFile,
    downloadImageZip,
    importExcel, // 新增导入Excel接口
    reFileNumber, // 新增重编档号接口
    renameDocFiles // 新增重命名Word文档接口
} from '@/api/newsPhotos'
import { useRouter } from 'vue-router'
import { useNewsStore } from '@/stores/newsStore'
import { saveAs } from 'file-saver'
import ExcelJS from 'exceljs'
import { modifyImageExif, getCurrentDateStr, safeFileName, normalizeImagePath, getOrgIssueName, isNull } from '@/utils/fileUtil'
import { getUnits } from '@/api/unitManagement'
import JSZip from 'jszip';
import FolderSelector from '@/components/FolderSelector.vue'

const fileTree = ref([])
const tableData = ref([])
const loading = ref(false)
const searchForm = ref({
    fileType: null,
    isMovedToArchive: null
})
const searchFormRef = ref(null)
const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
})
// 单位信息数据
const organizationData = ref([])
// 年份
const availableYears = ref([])

// 加载文件树
const loadFileTree = async () => {
    try {
        const res = await getFileTree()
        fileTree.value = [res] // 将根节点包装为数组
        // 从fileTree筛选出第一级目录
        availableYears.value = res.children.map(item => item.path && item.path.match(/^\d{4}$/))
        .filter(year => year)
        .map(year => year[0])
    } catch (error) {
        // ElMessage.error('加载文件树失败: ' + error.message)
    }
}

const filterOptions = [
    {
        label: 'JPG',
        value: 'JPG'
    },
    {
        label: 'JPEG',
        value: 'JPEG'
    },
    {
        label: 'GIF',
        value: 'GIF'
    },
    {
        label: 'PNG',
        value: 'PNG'
    },
    {
        label: 'BMP',
        value: 'BMP'
    },
    {
        label: 'TIF',
        value: 'TIF'
    },
    {
        label: 'TIFF',
        value: 'TIFF'
    },
    {
        label: 'RAW',
        value: 'RAW'
    },
    {
        label: 'CDR',
        value: 'CDR'
    },
    {
        label: 'AI',
        value: 'AI'
    },
    {
        label: 'PSD',
        value: 'PSD'
    },
    {
        label: 'XLS',
        value: 'XLS'
    },
    {
        label: 'XLSX',
        value: 'XLSX'
    },
    {
        label: 'DOC',
        value: 'DOC'
    },
    {
        label: 'DOCX',
        value: 'DOCX'
    },
    {
        label: 'MP3',
        value: 'MP3'
    },
    {
        label: 'MP4',
        value: 'MP4'
    },
    {
        label: 'WAV',
        value: 'WAV'
    },
    {
        label: 'MOV',
        value: 'MOV'
    },
    {
        label: 'M4A',
        value: 'M4A'
    },
    {
        label: 'MXF',
        value: 'MXF'
    },
    {
        label: 'PDF',
        value: 'PDF'
    },
    {
        label: 'PPTX',
        value: 'PPTX'
    },
    {
        label: 'CRX',
        value: 'CRX'
    },
    {
        label: 'JIF',
        value: 'JIF'
    }
]

// 选中项
const selectedItems = ref([])
const multipleTableRef = ref()

// 初始化
onMounted(() => {
    fetchData()
    loadFileTree()
})

// 获取数据
const fetchData = async () => {
    try {
        loading.value = true
        if (organizationData.value.length == 0) {
            const unitRes = await getUnits()
            organizationData.value = unitRes
        }
        const params = {
            page: pagination.value.currentPage - 1,
            size: pagination.value.pageSize,
        }
        // 遍历 searchForm 的字段，将有值的添加到 params
        Object.keys(searchForm.value).forEach(key => {
            const value = searchForm.value[key];
            if (value !== null && value !== undefined && value !== '') {
                // 特殊处理图片大小筛选
                if (key === 'fileSize') {
                    // 验证value是有效正整数
                    const numValue = Number(value)
                    if (Number.isInteger(numValue) && numValue > 0) {
                        params[key] = numValue
                    }
                } else {
                    params[key] = value
                }
            }
        });

        const response = await searchNewsPhotos(params);
        if (!response) return;
        tableData.value = response.content;
        tableData.value.forEach(async item => {
            if (item.imagePath) {
                const normalizedPath = normalizeImagePath(item.imagePath)
                item.imgSrc = import.meta.env.VITE_API_BASE_URL + '/static/' + normalizedPath
            }
        })
        pagination.value.total = response.totalElements || 0
    } catch (error) {
        // ElMessage.error('获取数据失败: ' + error.message)
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    pagination.value.currentPage = 1
    fetchData()
}

// 清空搜索
const handleSearchClear = () => {
    searchFormRef.value?.resetFields();
    handleSearch()
}

// 导入Excel
const handleExcelImport = async (file) => {
    try {
        const loadingInstance = ElMessage.info('正在导入Excel文件...', 0)
        
        const formData = new FormData()
        formData.append('file', file.raw)
        
        const result = await importExcel(formData)
        
        loadingInstance.close()
        
        if (!result) {
            ElMessage.success('Excel文件导入成功')
            fetchData() // 重新加载数据
        } else {
            ElMessage.error('Excel文件导入失败')
        }
    } catch (error) {
        ElMessage.error('Excel文件导入失败: ' + error.message)
    }
}

// 行点击
const handleRowClick = (row) => {
    console.log('Row clicked:', row)
    // 可以在这里实现行点击的逻辑，如查看详情等
}

// 分页大小改变
const handleSizeChange = (val) => {
    pagination.value.pageSize = val
    fetchData()
}

// 当前页改变
const handleCurrentChange = (val) => {
    pagination.value.currentPage = val
    fetchData()
}

const getImageUrl = async (fullPath) => {
    return
}

// 选中项变化回调
const handleSelectionChange = (val) => {
    selectedItems.value = val
}

// 批量删除
const handleBatchRemove = (isMovedToArchive) => {
    if (selectedItems.value.length === 0) return

    ElMessageBox.confirm(
        `确定要将选中的 ${selectedItems.value.length} 条数据设为${isMovedToArchive ? '【移馆】' : '【不移馆】'}吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        console.log(selectedItems)
        selectedItems.value.forEach(item => item.isMovedToArchive = isMovedToArchive)
        const result = await batchUpdateArchiveStatus({
            photoIds: selectedItems.value.map(item => item.photoId).join(','),
            isMovedToArchive
        })
        if (result) {
            ElMessage.success(`已更新${result}条数据`)
        }
    }).catch(() => {
        ElMessage.info('操作失败')
    })
}
// 批量迁移不移管照片
const handleBatchMove = (moveType) => {
  if (selectedItems.value.length === 0) return

  ElMessageBox.confirm(
    `确定要迁移选中的 ${selectedItems.value.length} 条数据吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用批量迁移API
      const response = await batchMoveArchive({
        photoIds: selectedItems.value.map(item => item.photoId).join(','),
        moveType
      })
      
      // 后端可能不返回数据，所以我们只检查是否发生异常
      // 如果没有异常，就认为操作成功
      ElMessage.success(`成功迁移 ${selectedItems.value.length} 条数据`)
      fetchData() // 重新加载数据
    } catch (error) {
      ElMessage.error('批量迁移失败: ' + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

function getPersonList(extendedData) {
    let personList = []
    if (extendedData) {
        try {
            personList = JSON.parse(extendedData)?.persons || []
        } catch (error) {
            console.log(error)
        }
    }
    return personList
}

function getImageInfo(data) {
    const info = []
    // if (data.imageFormat) info.push(data.imageFormat)
    if (data.imageSize) info.push(data.imageSize)
    if (data.extendedData) {
        const json = JSON.parse(data.extendedData)
        if (json) {
            const { image_dpi, image_height, image_width } = json
            if (image_width && image_height) info.push(image_width + '*' + image_height)
            if (image_dpi) info.push(image_dpi + 'dpi')
        }
    }
    return info.join('，')
}

const router = useRouter()
const newsStore = useNewsStore()
const handleEdit = (data) => {
    newsStore.setCurrentNews(data)
    router.push({ path: '/news-photo', query: { path: data.imagePath } })
}

const exportImageZip = async (images, type) => {
    const zip = new JSZip();
    let successCount = 0;
    const failures = [];
    const fileCountMap = {}; // 记录档号出现次数

    // 预处理图片URL
    const processedImages = images.map(item => ({
        ...item,
        imgSrc: item.imagePath
            ? import.meta.env.VITE_API_BASE_URL + '/static/' + normalizeImagePath(item.imagePath)
            : null
    })).filter(item => item.imgSrc);

    // 预扫描构建档号计数
    processedImages.forEach(img => {
        const fileNumber = img.fileNumber || '未命名';
        fileCountMap[fileNumber] = (fileCountMap[fileNumber] || 0) + 1;
    });

    // 并发控制（3个并发）
    const CONCURRENT_LIMIT = 3;
    const batchSize = Math.ceil(processedImages.length / CONCURRENT_LIMIT);

    for (let i = 0; i < processedImages.length; i += batchSize) {
        const batch = processedImages.slice(i, i + batchSize);

        await Promise.all(batch.map(async (img) => {
            try {
                let retryCount = 2;
                while (retryCount >= 0) {
                    try {
                        const modifiedBlob = await modifyImageExif(img.imgSrc, {
                            author: `${img.organization} ${img.journalists}` || '',
                            date: img.shootingDate
                        });

                        if (modifiedBlob) {
                            // 生成带序号的文件名
                            const fileNumber = img.fileNumber || '未命名';
                            const extension = (img.imageFormat || 'jpg').toLowerCase();

                            // 如果是重复档号则添加序号
                            let filename;
                            if (fileCountMap[fileNumber] > 1) {
                                const counter = (fileCountMap[fileNumber + '_counter'] =
                                    (fileCountMap[fileNumber + '_counter'] || 0) + 1);
                                filename = `${fileNumber}_${counter}.${extension}`;
                            } else {
                                filename = `${fileNumber}.${extension}`;
                            }

                            // 安全处理文件名
                            filename = safeFileName(filename);
                            zip.file(filename, modifiedBlob);
                            successCount++;
                            break;
                        }
                    } catch (e) {
                        if (retryCount === 0) {
                            failures.push({
                                fileNumber: img.fileNumber,
                                error: e.message
                            });
                            console.error(`处理失败 [${img.fileNumber}]:`, e);
                        }
                        retryCount--;
                        await new Promise(res => setTimeout(res, 1000));
                    }
                }
            } catch (e) {
                failures.push({
                    fileNumber: img.fileNumber,
                    error: 'FATAL: ' + e.message
                });
                console.error(`严重错误 [${img.fileNumber}]:`, e);
            }
        }));
    }

    // 生成报告（添加重名处理说明）
    const reportContent = [
        `=== 导出报告 ===`,
        `时间: ${new Date().toLocaleString()}`,
        `总计: ${processedImages.length} 张`,
        `成功: ${successCount} 张`,
        `失败: ${failures.length} 张`,
        // `重复档号文件: ${Object.keys(fileCountMap).filter(k => fileCountMap[k] > 1).length} 组`,
        ...(failures.length > 0 ? [
            '\n=== 失败列表 ===',
            ...failures.map(f => `• ${f.fileNumber}: ${f.error}`)
        ] : []),
        '\n命名规则:',
        '- 唯一档号: 档号.扩展名',
        '- 重复档号: 档号_序号.扩展名',
        '- 无名文件: 未命名_序号.扩展名'
    ].join('\n');

    zip.file('REPORT.txt', reportContent);

    // 生成压缩包
    const content = await zip.generateAsync({
        type: 'blob',
        compression: 'DEFLATE',
        compressionOptions: { level: 6 }
    });

    saveAs(content, `新闻照片${type}${getCurrentDateStr()}.zip`);
    return {
        successCount,
        failureCount: failures.length,
        duplicatedFiles: Object.keys(fileCountMap).filter(k => fileCountMap[k] > 1).length
    };
};

// 导出处理函数
const handleExport = async (command) => {
    try {
        // 显示加载提示
        const loadingInstance = ElMessage.info('正在准备导出数据...', 0)

        // 设置导出参数
        let exportParams = {
            page: 0,
            size: 110000 // 获取足够大的数据量
        }
        exportParams.downloadType = '1'
        // 根据选择的类型添加筛选条件
        if (command === 'moved') {
            exportParams.isMovedToArchive = true
            exportParams.downloadType = '2'
        } else if (command === 'notMoved') {
            exportParams.isMovedToArchive = false
            exportParams.downloadType = '3'
        } else if (command === 'filted') {
            const params = {
                page: pagination.value.currentPage - 1,
                size: pagination.value.pageSize
            }
            exportParams = { ...searchForm.value, downloadType: '0', ...params }
        } else if (command === 'searchAll') {
            exportParams = { ...searchForm.value, downloadType: '4', ...exportParams }
        }

        // 调用API获取数据
        const response = await searchNewsPhotos(exportParams)
        if (!response || !response.content || response.content.length === 0) {
            ElMessage.warning('没有数据可导出')
            loadingInstance.close()
            return
        }

        // 数组排序
        response.content.sort((a, b) => {
            // 首先，将null或空的fileNumber放到最后
            if (!a.fileNumber && !b.fileNumber) return 0;
            if (!a.fileNumber) return 1;
            if (!b.fileNumber) return -1;
            
            // 然后按fileNumber进行自然排序
            return (a.fileNumber || '').localeCompare(b.fileNumber || '', undefined, { numeric: true, sensitivity: 'base' });
        })
        // console.log('response', response)

        // 创建工作簿
        const workbook = new ExcelJS.Workbook()
        const worksheet = workbook.addWorksheet('新闻照片数据')
        const style = {
            font: {
                name: 'Arial',
                size: 10
            }
        }

        // 设置列头
        worksheet.columns = [
            { header: '案卷级档号', key: '', width: 20 },
            { header: '文件级档号', key: 'fileNumber', width: 20 },
            { header: '全宗号', key: 'oNumber', width: 15 },
            { header: '档案门类代码', key: 'dNumber', width: 15 },
            { header: '年度', key: 'yNumber', width: 10 },
            { header: '保管期限', key: 'lNumber', width: 15 },
            { header: '机构（问题）代码', key: 'jNumber', width: 20 },
            { header: '张号', key: 'zNumber', width: 10 },
            { header: '题名', key: 'imageTitle', width: 40 },
            { header: '日期', key: 'shootingDate', width: 15 },
            { header: '拍摄地点', key: 'shootingLocation', width: 25 },
            { header: '人物', key: 'persons', width: 30 },
            { header: '摄影者', key: 'journalists', width: 20 },
            { header: '背景', key: 'imageBackground', width: 20 },
            { header: '计算机文件格式', key: 'imageFormat', width: 15 },
            { header: '计算机文件大小', key: 'imageSize', width: 15 },
            { header: '生成方式', key: '', width: 15 },
            { header: '载体形态', key: '', width: 15 },
            { header: '密级', key: '', width: 10 },
            { header: '解密审核', key: '', width: 15 },
            { header: '开放标识', key: '', width: 15 },
            { header: '销毁情况', key: '', width: 15 },
            { header: '附注', key: '', width: 30 }
        ].map(item => {
            return { ...item, style }
        })

        // 添加数据行
        response.content.forEach(item => {
            // 处理人物信息
            let persons = ''
            let oNumber = '' // 全宗号
            let dNumber = '' // 档案门类代码
            let yNumber = '' // 年度
            let lNumber = '' // 保管期限
            let jNumber = '' // 机构问题
            let zNumber = '' // 张号
            try {
                const extendedData = JSON.parse(item.extendedData || '{}')
                if (extendedData.persons && Array.isArray(extendedData.persons)) {
                    persons = extendedData.persons.map(p =>
                        // `${p.position || ''}${p.name || ''}(${p.positionInImage || ''})`
                        `${p.name || ''} ${((p.positionInImage || p.position) ? '（' + ((p.position && p.positionInImage) ? [p.position, p.positionInImage].join('，') : (p.position || p.positionInImage)) + '）' : '')}`
                    ).join(', ')
                }
                const fileNumber = item.fileNumber || ''
                const parts = fileNumber.split('-')
            if (parts.length >= 5) {
                oNumber = parts[0]  // 全宗号: 0003
                dNumber = parts[1].split('•')[0]  // 档案门类代码: ZP
                yNumber = parts[1].split('•')[1]  // 年度: 2025
                lNumber = parts[2]  // 保管期限: D30
                jNumber = parts[3]  // 机构问题: RMT
                zNumber = parts[4]  // 张号: 0008
            }
            } catch (e) {
                console.error('解析人物信息失败', e)
            }

            // 添加行数据
            worksheet.addRow({
                fileNumber: item.fileNumber || '',
                imageTitle: item.imageTitle ? item.imageTitle.replace(/[!-~]/g, (match) => {
                    // 将半角符号转换为全角符号（空格除外）
                    return String.fromCharCode(match.charCodeAt(0) + 0xFEE0)
                }) : '', // 题目半角符号转换为全角
                shootingDate: item.shootingDate ? item.shootingDate.replace(/-/g, '') : '',
                shootingLocation: item.shootingLocation || '',
                persons: persons,
                journalists: item.journalists || '',
                imageBackground: item.imageBackground || '',
                imageFormat: item.imageFormat || '',
                imageSize: item.imageSize || '',
                oNumber: oNumber,
                dNumber: dNumber,
                yNumber: yNumber,
                lNumber: lNumber,
                jNumber: jNumber,
                zNumber: zNumber
            })
        })

        // 设置标题行样式
        worksheet.getRow(1).eachCell(cell => {
            cell.font = { bold: true }
            cell.fill = {
                type: 'pattern',
                pattern: 'solid',
                fgColor: { argb: 'FFD9D9D9' }
            }
        })

        // 生成Excel文件
        const buffer = await workbook.xlsx.writeBuffer()
        const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })

        // 生成文件名
        const now = new Date()
        const dateStr = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`
        const timeStr = `${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`
        const typeName = command === 'filted' ? '单页数据' : command === 'moved' ? '移馆数据' : command === 'notMoved' ? '不移馆数据' : '全部数据'

        saveAs(blob, `新闻照片${typeName}_${dateStr}_${timeStr}.xlsx`)

        // 关闭加载提示
        loadingInstance.close()
        ElMessage.success('Excel导出成功')
        // 导出图片压缩包
        ElMessage.info('开始导出图片压缩包...')
        const isElectron = navigator.userAgent.includes('Electron')
        if (isElectron) {
            const successCount = await exportImageZip(response.content, typeName);
            ElMessage.success(`导出完成，成功处理 ${successCount}/${response.content.length} 张图片`);
        } else {
            // await downloadImageZip(exportParams)
            // ElMessage.success(`导出完成，成功处理`)
        }
    } catch (error) {
        ElMessage.error('导出失败: ' + error.message)
        console.error('导出失败', error)
    }
}

const selectedFolder = ref(null)
const handleFolderSelected = (folder) => {
    selectedFolder.value = folder
    searchForm.value.like_imagePath = selectedFolder.value.path
}

// 添加导入目录相关的状态和函数
const importDialogVisible = ref(false)
const tempFileTree = ref([])
const selectedImportFolder = ref(null)

// 导入目录处理函数
const handleImport = async () => {
    try {
        // 显示加载提示
        const loadingInstance = ElMessage.info('正在加载目录树...', 0)
        
        // 重新加载文件树（使用已有的api/documents/tree接口）
        const res = await getFileTree()
        tempFileTree.value = [res] // 将根节点包装为数组
        
        // 关闭加载提示
        loadingInstance.close()
        
        // 显示目录选择对话框
        importDialogVisible.value = true
    } catch (error) {
        ElMessage.error('加载目录树失败: ' + error.message)
        console.error('加载目录树错误:', error)
    }
}

// 处理选择的目录
const handleImportFolderSelect = (folder) => {
    selectedImportFolder.value = folder
}

// 确认导入目录
const confirmImport = () => {
    if (!selectedImportFolder.value) {
        ElMessage.warning('请选择要导入的目录')
        return
    }
    
    // 显示加载状态
    loading.value = true
    
    // 调用 importFile API，参数格式为 {path: 'xxx'}
    importFile({ path: selectedImportFolder.value.path })
        .then(() => {
            // 将选择的目录应用到搜索条件中
            searchForm.value.like_imagePath = selectedImportFolder.value.path
            handleSearch()
            
            // 显示成功提示
            ElMessage.success(`已导入目录: ${selectedImportFolder.value.name}`)
        })
        .catch(error => {
            ElMessage.error(`导入目录失败: ${error.message || '未知错误'}`)
        })
        .finally(() => {
            // 关闭对话框
            importDialogVisible.value = false
            
            // 重置选择
            selectedImportFolder.value = null
            
            // 隐藏加载状态
            loading.value = false
        })
}

// 取消导入
const cancelImport = () => {
    importDialogVisible.value = false
    selectedImportFolder.value = null
}

// 获取单位名称
const getOrgName = (value) => {
    if (value == null) {
        return ''
    }
    const orgData = JSON.parse(JSON.stringify(organizationData.value))
    const orgName = getOrgIssueName(value, orgData)
    return orgName
}

// 档案号重编处理函数
const handleRenumber = (year) => {
    ElMessageBox.confirm(
        `确定重编 ${year} 目录下的档号吗？`,
        '档案号重编确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        // 这里应该调用实际的重编API
        await reFileNumber({ path: year })
        ElMessage.success(`已将档号重新编排`)
    }).catch(() => {
        // ElMessage.info('已取消操作')
    })
}

// 重命名Word文档相关状态
const renameWordDialogVisible = ref(false)
const renameWordForm = ref({
    rootPath: ''
})
const renameWordFormRef = ref(null)

// 显示重命名Word对话框
const showRenameWordDialog = () => {
    renameWordDialogVisible.value = true
    renameWordForm.value.rootPath = ''
}

// 确认重命名Word文档
const confirmRenameWord = async () => {
    if (!renameWordForm.value.rootPath) {
        ElMessage.warning('请输入名称')
        return
    }
    
    try {
        await renameDocFiles({
            rootPath: renameWordForm.value.rootPath
        })
        ElMessage.success('Word文档重命名成功')
        renameWordDialogVisible.value = false
    } catch (error) {
        ElMessage.error('重命名失败: ' + error.message)
    }
}

// 取消重命名Word文档
const cancelRenameWord = () => {
    renameWordDialogVisible.value = false
}

</script>

<style scoped>

.search-container {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

.search-container {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

/* 导出导入按钮容器 */
.export-import-container {
    float: right;
    margin-right: 0;
}

/* 导入按钮样式 */
.import-btn {
    margin-right: 10px;
}

/* 目录选择器容器 */
.folder-selector-container {
    display: flex;
    align-items: center;
}

/* 对话框操作按钮容器 */
.dialog-actions {
    text-align: right;
    margin-top: 20px;
}

.search-form {
    display: flex;
    align-items: center;
}

.search-form .el-form-item--label-right {
    margin-right: 12px;
}

.search-form .search-right-btns {
    flex: 1;
}
.search-form .search-right-btns /deep/.el-form-item__content {
    display: flex;
    justify-content: flex-end;
}
</style>